package com.shanjupay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.shanjupay.common.exception.BusinessException;
import com.shanjupay.common.exception.CommonErrorCode;
import com.shanjupay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.sql.BatchUpdateException;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: shanjupay
 * @package: com.shanjupay.merchant.service.impl
 * @className: SmsServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2023/12/2 21:31
 * @version: 1.0
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取短信代码
     *
     * @param phone 电话
     * @return {@link String}
     */
    @Override
    public String getSmsCode(String phone) throws BusinessException {
        String url = smsUrl + "/generate?name=sms&effectiveTime=" + effectiveTime;
        System.out.println("调用短信微服务发送验证码" + url);
        Map<String, Object> body = new HashMap<String, Object>();
        body.put("mobile", phone);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity entity = new HttpEntity(body, httpHeaders);
        Map responseMap;
        try {
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
            log.info("调用短信微服务发送验证码: 返回值:{}", JSON.toJSONString(exchange));
            responseMap = exchange.getBody();
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            // throw new RuntimeException("发送验证码出错");
            throw new BusinessException(CommonErrorCode.E_100102);
        }
        if (responseMap == null || responseMap.get("result") == null) {
            // throw new RuntimeException("发送验证码出错");
            throw new BusinessException(CommonErrorCode.E_100102);
        }
        Map resultMap = (Map) responseMap.get("result");
        return resultMap.get("key").toString();
    }

    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) throws BusinessException{
        // verifiykey:验证码的key       verifiyCode:验证码
        String url = smsUrl + "/verify?name=sms&verificationCode=" + verifiyCode + "&verificationKey=" + verifiyKey;
        Map<String, Object> responseMap = null;
        try {
            //请求校验验证码
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            responseMap = exchange.getBody();
            log.info("校验验证码，响应内容:" + JSON.toJSONString(responseMap));
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage() + e);
            // throw new RuntimeException("验证码错误");
            throw new BusinessException(CommonErrorCode.E_100102);
        }
        if (responseMap == null || responseMap.get("result") == null || !(Boolean) responseMap.get("result")) {
            // throw new RuntimeException("验证码错误");
            throw new BusinessException(CommonErrorCode.E_100102);
        }
    }
}
